<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="department_box box-card">
        <DeptOption :row="company" :is-root="true" @isShowDeptAdd="isShowDeptAdd" />
        <el-tree :data="depts" :props="defaultProps" :default-expand-all="true">
          <template slot-scope="scope">
            <DeptOption :row="scope.data" @click-edit="clickEdit" @isShowDeptAdd="isShowDeptAdd" @onDel="loadDepartment()" />
          </template>
        </el-tree>
      </el-card>
    </div>
    <DeptAdd ref="addDept" :row="deptRow" :dialog-visible.sync="dialogVisible" @add-success="loadDepartment" @isShowDeptAdd="isShowDeptAdd" />
  </div>
</template>

<script>
import { getDepartment } from '@/api/department.js'
import { transListToTree } from '@/utils'
import DeptOption from './components/Dept-option.vue'
import DeptAdd from './components/Dept-add.vue'
export default {
  name: 'Departments',
  components: {
    DeptOption,
    DeptAdd
  },
  data() {
    return {
      defaultProps: {
        label: 'name'
      },
      depts: [],
      company: {},
      dialogVisible: false,
      deptRow: {}
    }
  },
  created() {
    this.loadDepartment()
  },

  methods: {
    async loadDepartment() {
      const res = await getDepartment()
      this.depts = transListToTree('', res.depts)
      this.company = { name: res.companyName, manager: '负责人', children: transListToTree('', res.depts) }
    },
    isShowDeptAdd(data) {
      this.deptRow = data
      this.dialogVisible = !this.dialogVisible
    },
    clickEdit(data) {
      this.deptRow = data
      this.dialogVisible = !this.dialogVisible
      setTimeout(() => {
        this.$refs.addDept.setForm()
      })
    }
  }
}
</script>

<style scoped lang='scss'>
  .department_box{
    .el-tree{
      margin-top: 10px;
      border-top: 1px solid #ccc;
    }
  }
</style>
